package com.example.function.auth.controller;


import com.example.common.support.*;
import com.example.function.auth.requestBody.UserRequestBody;
import com.example.service.JwtAuthService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
public class JwtAuthController {
    @Resource
    JwtAuthService jwtAuthService;


    /**
     * 如果json请求：参数前要加@RequestBody User user
     * {
     * "username":"admin",
     * "password":"123456",
     * "userType":0
     * }
     */
    @PostMapping(value = "/auth/token")
    @CP_OperateLog(value = "用户登录", type = CP_GlobalNamingConstant.OPERATE_LOGIN)
    public AjaxResponse login(@RequestBody UserRequestBody user, HttpServletRequest request) {

        if (user == null || !StringUtils.hasText(user.getLoginName())
                || !StringUtils.hasText(user.getPassword())) {
            return AjaxResponse.error(
                    new CustomException(CustomExceptionType.USER_INPUT_ERROR,
                            "用户名或者密码不能为空"));
        }
        try {
            request.setAttribute("username",user.getLoginName());
            return AjaxResponse.success(jwtAuthService.login(user.getLoginName(), user.getPassword(),user.getUserType()));
        } catch (CustomException e) {
            return AjaxResponse.error(e);
        }
    }

    @RequestMapping(value = "/auth/refreshtoken")
    @CP_OperateLog(value = "刷新token", type = CP_GlobalNamingConstant.OPERATE_AUTH)
    public AjaxResponse refresh(@RequestHeader("${jwt.header}") String token) {
        return AjaxResponse.success(jwtAuthService.refreshToken(token));
    }


    @RequestMapping(value = "/auth/validatetoken")
    @CP_OperateLog(value = "验证token是否到期", type = CP_GlobalNamingConstant.OPERATE_AUTH)
    public AjaxResponse validate(@RequestHeader("${jwt.header}") String token) {
        return AjaxResponse.success(jwtAuthService.validateToken(token));
    }

}
